package com.example.feifei.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;

/**
 * 波浪线动图（贝塞尔曲线）
 * Created by feifei on 2017/7/25.
 */

public class BezierView extends View{

    private int screenWidth;//波浪线宽度
    private float xoffset = 0;

    private Paint paint;
    private Path path;


    public BezierView(Context context) {
        super(context);
        initView(context);
    }

    public BezierView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public BezierView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context){
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();

        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.STROKE);
        path = new Path();

        ValueAnimator animator = new ValueAnimator();
        animator.setFloatValues(0,screenWidth);
        animator.setDuration(1000);
        animator.setRepeatCount(-1);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                xoffset = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
        animator.start();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        path.reset();

        path.moveTo(0 + xoffset, 200);
        path.quadTo(screenWidth / 4 + xoffset, 0, screenWidth / 2 + xoffset, 200);
        path.moveTo(screenWidth / 2 + xoffset, 200);
        path.quadTo(screenWidth / 4 * 3 + xoffset, 400, screenWidth + xoffset, 200);


        path.moveTo(0 + xoffset - screenWidth, 200);
        path.quadTo(screenWidth / 4 + xoffset - screenWidth, 0, screenWidth / 2 + xoffset - screenWidth, 200);
        path.moveTo(screenWidth / 2 + xoffset - screenWidth, 200);
        path.quadTo(screenWidth / 4 * 3 + xoffset - screenWidth, 400, screenWidth + xoffset - screenWidth, 200);

        canvas.drawPath(path, paint);
    }
}
